package org.alive.ee.app.repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Component;

@Component("jdbcTemplate")
public class ExtendJdbcTemplate extends JdbcTemplate {

	public ExtendJdbcTemplate() {
		super();
	}

	@Autowired
	public ExtendJdbcTemplate(DataSource dataSource) {
		super(dataSource);
	}

	public ExtendJdbcTemplate(DataSource dataSource, boolean lazyInit) {
		super(dataSource, lazyInit);
	}

	/**
	 * 
	 */
	public <T> T  query(String sql, PreparedStatementSetter pss, ResultSetExtractor<T> rse) throws DataAccessException {
		return query(new ExtendPreparedStatementCreator(sql), pss, rse);
	}
}

class ExtendPreparedStatementCreator implements PreparedStatementCreator {

	/** SQL */
	private final String sql;

	public ExtendPreparedStatementCreator(String sql) {
		this.sql = sql;
	}

	/**
	 * cursor
	 */
	public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
		return con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
	}

	public String getSql() {
		return this.sql;
	}
}